package reggie.ruiji.controller;
import com.alibaba.druid.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reggie.ruiji.common.R;
import reggie.ruiji.pojo.User;
import reggie.ruiji.untils.SMSUtils;
import reggie.ruiji.untils.ValidateCodeUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController
{
    @Autowired
    private RedisTemplate redisTemplate;



    @PostMapping("/sendMsg")
        public R<String> sendMsg( @RequestBody String  phone, HttpServletRequest session)
    {
        /*String  phone = user.getPhone();*/
        if (StringUtils.isEmpty(phone))
        {
            String code= ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            try {
                SMSUtils.sendMessage(phone,code);//将生成的验证码通过短信发送
               /* session.setAttribute(phone,code);//将生成的验证码保存到Session */
                redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);//将生成的验证码存入Redis缓存
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return R.success("手机验证码短信发送成功");
        }
        return R.error("手机验证码短信发送失败");

    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map map, HttpServletRequest session)//移动端用户登录
    {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

/*
        //从Session中获取保存的验证码
        Object codeInSession = session.getAttribute(phone);
*/

        //从Redis中获取获取缓存的验证码
        Object codeInSession=redisTemplate.opsForValue().get(phone);

        if (codeInSession != null && codeInSession.equals(code))
        {

            //如果用户登录成功，我们就删除Redis中缓存的验证码
            redisTemplate.delete(phone);


            return R.success("登录成功");
        }
        return R.error("登录失败");

    }
}
